package com.lianyu.wangyiyun.fragment;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.lianyu.wangyiyun.databinding.MusicListBinding;
import com.lianyu.wangyiyun.databinding.MusictItemBinding;
import com.lianyu.wangyiyun.model.Mp3Info;
import com.lianyu.wangyiyun.model.MusicListViewModel;
import com.lianyu.wangyiyun.service.MusicService;
import com.lianyu.wangyiyun.utils.FindLocalSongs;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import java.util.List;

/**
 * @author Chen Yuguang
 * @date 2021/5/8 5:23
 */
public class LocalFragment extends AbstractLazyFragment {

    private RefreshLayout refreshLayout;
    private MusicListViewModel musicListViewModel;
    private MusicListViewModel mainMusicListViewModel;

    private final DiffUtil.ItemCallback<Mp3Info> diffCallback =
            new DiffUtil.ItemCallback<Mp3Info>() {

                @Override
                public boolean areItemsTheSame(@NonNull Mp3Info oldItem, @NonNull Mp3Info newItem) {
                    return oldItem.getId() == newItem.getId();
                }

                @Override
                public boolean areContentsTheSame(@NonNull Mp3Info oldItem, @NonNull Mp3Info newItem) {
                    return oldItem.equals(newItem);
                }
            };

    private final RecyclerAdapter recyclerAdapter = new RecyclerAdapter();

    public void setList(List<Mp3Info> list) {
        musicListViewModel.getMusicLiveData().setValue(list);
    }

    @Override
    protected View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        MusicListBinding musicListBinding = MusicListBinding.inflate(inflater, container, false);
        RecyclerView musicRecyclerView = musicListBinding.musicRecyclerView;
        Context context = getContext();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置布局管理者（竖向的线性布局）
        musicRecyclerView.setLayoutManager(linearLayoutManager);
        //设置适配器
        musicRecyclerView.setAdapter(recyclerAdapter);
        TextView nilView = musicListBinding.nilView;
        refreshLayout = musicListBinding.smartRefreshLayout;
        //是否在刷新的时候禁止列表的操作
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            if (context != null) {
                //刷新获取本地音乐列表给viewModel
                musicListViewModel.getMusicLiveData().setValue(FindLocalSongs.getMp3Infos(context.getContentResolver()));
            }
            refreshLayout.finishRefresh();
        });
        musicListViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(MusicListViewModel.class);
        //将viewModel与recyclerView的适配器列表绑定在一起
        musicListViewModel.getMusicLiveData().observe(this, list -> {
            if (list.size() == 0) {
                //显示空布局
                if (nilView.getVisibility() == View.GONE) {
                    nilView.setVisibility(View.VISIBLE);
                }
            } else {
                if (nilView.getVisibility() == View.VISIBLE) {
                    nilView.setVisibility(View.GONE);
                }
            }
            //提交列表给适配器
            recyclerAdapter.submitList(list);
        });
        FragmentActivity fragmentActivity = getActivity();
        if (fragmentActivity != null) {
            mainMusicListViewModel = new ViewModelProvider(fragmentActivity, new ViewModelProvider.NewInstanceFactory()).get(MusicListViewModel.class);
        }
        return musicListBinding.getRoot();
    }

    @Override
    protected void initData() {
        //如果ViewModel中LiveData的List为null则刷新
        if (musicListViewModel.getMusicLiveData().getValue() == null) {
            //自动刷新
            refreshLayout.autoRefresh();
        }
    }

    private class RecyclerAdapter extends ListAdapter<Mp3Info, RecyclerAdapter.ViewHolder> {

        protected RecyclerAdapter() {
            super(diffCallback);
        }

        //创建视图
        @Override
        public @NonNull
        RecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            MusictItemBinding musictItemBinding = MusictItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
            return new RecyclerAdapter.ViewHolder(musictItemBinding);
        }

        //数据绑定
        @Override
        public void onBindViewHolder(@NonNull RecyclerAdapter.ViewHolder holder, int position) {
            Mp3Info mp3Info = getCurrentList().get(position);
            holder.title.setText(mp3Info.getTitle());
            holder.artist.setText(mp3Info.getArtist());
            holder.itemView.setOnClickListener(v -> {
                Context context = getContext();
                Intent serviceIntent = new Intent(context, MusicService.class);
                //传送url给service播放
                serviceIntent.putExtra("url", mp3Info.getUrl());
                serviceIntent.putExtra("title", mp3Info.getTitle());
                serviceIntent.putExtra("artist", mp3Info.getArtist());
                //设置要传给mainActivity的viewModel值（点击的播放列表）
                mainMusicListViewModel.getMusicLiveData().setValue(recyclerAdapter.getCurrentList());
                //设置要传给mainActivity的viewModel值（播放的位置）
                mainMusicListViewModel.getPositionLiveData().setValue(position);
                if (context != null) {
                    //启动播放服务
                    context.startService(serviceIntent);
                }
            });
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            public TextView title, artist;

            public ViewHolder(@NonNull MusictItemBinding musictItemBinding) {
                super(musictItemBinding.getRoot());
                title = musictItemBinding.title;
                artist = musictItemBinding.artist;
            }
        }

    }

}
